package com.tuzhi.convert.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class CacheUtil {

    private Logger log = LoggerFactory.getLogger(CacheUtil.class);

    @Value("${convert.filepath.cacheFilePath}")
    private String cacheFilePath;

    private final String cacheFileName = "modeling.cache";

    private Map<String,String> cacheMap;

    @Value("${cache.expires}")
    private Long expiresTime;

    @PostConstruct
    private void init(){
        cacheMap = new HashMap<>();
        try {
            File cacheFile = new File(cacheFilePath + File.separator + cacheFileName);
            if (cacheFile.exists()) {
                FileReader fr = new FileReader(cacheFile);
                BufferedReader bf = new BufferedReader(fr);
                List<String> arrayList = new ArrayList<>();
                String str;
                // 按行读取字符串
                while ((str = bf.readLine()) != null) {
                    arrayList.add(str);
                }
                bf.close();
                fr.close();

                arrayList.forEach(cache -> {
                    String[] cacheStr = cache.trim().split(",");
                    cacheMap.put(cacheStr[0], cacheStr[1]);
                });
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info("获取缓存异常!");
        }
    }

    public Boolean getCache(String key) {
        if(cacheMap == null){
            init();
        }
        String cacheTimeStr = cacheMap.get(key);
        if(cacheTimeStr != null && StringUtils.isNotBlank(cacheTimeStr)){
            Date cacheTime = null;
            try {
                cacheTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(cacheTimeStr);
                int compareTo  = new Date().compareTo(cacheTime);
                if(compareTo < expiresTime){//未过期
                    return true;
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    public void setCache(String key,String value) throws Exception {
        File cacheFile = new File(cacheFilePath+File.separator+cacheFileName);
        FileWriter fw = new FileWriter(cacheFile,true);
        fw.write(key+","+value+"\n");
        fw.close();
        if(cacheMap == null){
            init();
        }
        cacheMap.put(key,value);
    }

}
